package com.gary.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gary.entity.*;
//import com.gary.service.CmdService;
import com.gary.util.ConsulUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author peng_rui
 * @date 2022/2/15
 */
@Slf4j
@RestController
public class ConsulProviderOneController {

    private static final String ALERT_FIND_ALL_APP_URL = "http://localhost:10049/api/arch/ac/application/find-all";
    @Resource
    private ConsulUtil consulUtil;
    @Resource
    private RestTemplate restTemplate;
//    @Resource
//    private CmdService cmdService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping(value = "/consul/provider/one", method = RequestMethod.GET)
    public String providerOne() {
        System.out.println("providerOne");
        return "providerOne";
    }

    @RequestMapping(value = "/consul/get", method = RequestMethod.GET)
    public GaryConsul getValue(@RequestParam("port") Integer port) {
        GaryConsul value = consulUtil.getValue("/" + "120.55.99.182:" + port, GaryConsul.class);
        System.out.println(JSON.toJSONString(value));
        return value;
    }

    @RequestMapping(value = "/consul/update", method = RequestMethod.GET)
    public String updateValue(@RequestParam("port") Integer port) {
        GaryConsul garyConsul = new GaryConsul();
        garyConsul.setIp("120.55.99.182");
        garyConsul.setPort(port);
        garyConsul.setName("gary");
        garyConsul.setProjectId(10043);
        String key = "/" +  garyConsul.getIp() + ":" + garyConsul.getPort();
        String result = consulUtil.update(key, garyConsul);
        return result;
    }

    @RequestMapping(value = "/consul/delete", method = RequestMethod.GET)
    public String deleteValue(@RequestParam("port") Integer port) {
        String result = consulUtil.delete("/" + "120.55.99.182:" + port);
        return result;
    }

    @RequestMapping(value = "/consul/keys", method = RequestMethod.GET)
    public List<String> getAllKeys() {
        List<String> allKeys = consulUtil.getAllKeys();
        return allKeys;
    }

    @RequestMapping(value = "/consul/values", method = RequestMethod.GET)
    public List<GaryConsul> getAllValues() {
        List<GaryConsul> allValue = consulUtil.getAllValue(GaryConsul.class);
        return allValue;
    }

    @RequestMapping(value = "/healthCheck", method = RequestMethod.GET)
    public HealthCheckResp healthCheck(@RequestParam("ip")  String ip,@RequestParam("port")  Integer port) {
        String url = "http://" + ip + ":" + port + "/actuator/health";
        HttpHeaders headers = new HttpHeaders();
        HealthCheckResp resp = new HealthCheckResp();
        resp.setIp(ip);
        resp.setPort(port);
        resp.setAppName("gary-center");
        try {
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
            String json = response.getBody();
            Map map = JSON.parseObject(json, Map.class);
            resp.setStatus((String) map.get("status"));
            if (map.get("details") != null) {
                JSONObject jsonObject = (JSONObject) map.get("components");
                String json2 = JSON.toJSONString(jsonObject);
                resp.setDetails(JSON.parseObject(json2, Map.class));
            }
            return resp;
        } catch (RestClientException e) {
            log.error("seq = {} 应用健康检查失败 ", "500", e);
        }
        resp.setStatus("DOWN");
        return resp;
    }

    @RequestMapping(value = "/getAllApp", method = RequestMethod.GET)
    public List<ApplicationVO> getAllApp() {
        URI uri = URI.create(ALERT_FIND_ALL_APP_URL);
        final RequestEntity.BodyBuilder requestBuilder = RequestEntity.method(HttpMethod.GET, uri);

        requestBuilder.accept(MediaType.ALL);
        requestBuilder.contentType(MediaType.APPLICATION_JSON);
        RequestEntity<Object> requestEntity = requestBuilder.body(null);
        ParameterizedTypeReference<ApiResult<List<ApplicationVO>>> returnType
                = new ParameterizedTypeReference<ApiResult<List<ApplicationVO>>>() {};
        ResponseEntity<ApiResult<List<ApplicationVO>>> responseEntity = restTemplate.exchange(requestEntity, returnType);
        ApiResult<List<ApplicationVO>> body = responseEntity.getBody();
        List<ApplicationVO> data = body.getData();
        return data;
    }

    public StringBuilder curlTest() {
        String[] cmds = {"curl","http://192.168.x.xxx:8900/v1","-d",};
        ProcessBuilder process = new ProcessBuilder(cmds);
        try {
            Process p = process.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
            return builder;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/cmd-service", method = RequestMethod.GET)
    public List<CmdbInfo> cmdService() {
        List<CmdbInfo> cmdbInfo = null;//cmdService.getCmdbInfo();
        System.out.println(JSON.toJSONString(cmdbInfo));
        String cmdbJson = JSON.toJSONString(cmdbInfo);
//        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
//        redisTemplate.boundValueOps("GARY_CMDBINFO").set(cmdbInfo);
//        redisTemplate.boundValueOps("GARY_CMDBINFO_JSON").set(cmdbJson);
        return cmdbInfo;
    }

    @RequestMapping(value = "/get-cmdb-info", method = RequestMethod.GET)
    public List<CmdbInfo> getCmdInfo() {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        List<CmdbInfo> cmdbInfoList = (List<CmdbInfo>) ops.get("GARY_CMDBINFO");
        String cmdbinfoJson = (String) ops.get("GARY_CMDBINFO_JSON");
        return cmdbInfoList;
    }
}
